#include "wikiimportdatasetdialog.h"
#include "response.h"
#include "ui_wikiimportdatasetdialog.h"

#include <QClipboard>
#include <QFileDialog>
#include <QJsonDocument>
#include <QMessageBox>

#include <dialog/subdialog/importnetworkdialog.h>

WikiImportDataSetDialog::WikiImportDataSetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::WikiImportDataSetDialog)
{
    ui->setupUi(this);
}

WikiImportDataSetDialog::~WikiImportDataSetDialog()
{
    delete ui;
}

void WikiImportDataSetDialog::on_btn_import_paste_clicked()
{
    QClipboard *clipboard = qApp->clipboard();
    ui->plain_content->setPlainText(clipboard->text());
}

void WikiImportDataSetDialog::on_btn_done_clicked()
{
    auto content = ui->plain_content->toPlainText();

    QJsonParseError error;
    QJsonDocument document = QJsonDocument::fromJson(content.toUtf8(), &error);

    if (error.error != QJsonParseError::NoError) {
        QMessageBox::critical(this, "错误信息", "导入的数据不是正常 json 数据:\n" + error.errorString());
        return;
    }

    // 数据检查
    if (document.isObject()) {
        m_dataset.append(Response(0, content).toMap());
    }

    if (document.isArray()) {
        m_dataset = Response(0, content).toList();
    }

    accept();
}

void WikiImportDataSetDialog::setData(const QString &newData)
{
    m_data = newData;
    ui->plain_content->setPlainText(m_data);
}

void WikiImportDataSetDialog::on_btn_import_file_clicked()
{
    QString filepath = QFileDialog::getOpenFileName(this, "选择文件", "", "Json (*.json)");
    if (filepath.isEmpty()) return;

    QFile file(filepath);
    file.open(QFile::ReadOnly);
    setData(file.readAll());
    file.close();
}

QVariantList WikiImportDataSetDialog::dataset() const
{
    return m_dataset;
}


void WikiImportDataSetDialog::on_btn_import_network_clicked()
{
    ImportNetworkDialog dialog;
    if (dialog.exec() == QDialog::Accepted) {
        ui->plain_content->setPlainText(dialog.content());
    }
}

